package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.Service.IUserInfoRedisService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决跨域拦截以及静态页面访问问题
        //HandlerMethod h = (HandlerMethod) handler;
        if (!(handler instanceof HandlerMethod)) {
            //即如果现在handler方法不是HandlerMethod的实例方法,直接放行
            return true;
        }
        //从请求头中得到数据
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);

        HandlerMethod h = (HandlerMethod) handler;
        //如果貼有註解,進行判斷
        if (h.hasMethodAnnotation(RequireLogin.class)) {
            if (user == null) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //没贴注解的直接放行
        return true;
    }
}